package ah.szxy.service.impl;

import ah.szxy.domain.AccountTbl;
import ah.szxy.domain.AccountTblExample;
import ah.szxy.mapper.AccountTblMapper;
import ah.szxy.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;


/**
 * 删减账户业务
 *
 * @author caohaiyang
 * @create 2020-09-17 上午 10:16
 */
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountTblMapper accountTblMapper;

    public static final Logger log = LoggerFactory.getLogger(AccountServiceImpl.class);


    @Transactional
    @Override
    public void debit(String userName, int money) {
        log.info("对用户{} 进行账户金额的扣减, 扣减金额为{} .",userName,money);
        //1. 查询当前用户
        AccountTblExample tblExample = new AccountTblExample();
        tblExample.createCriteria().andUserIdEqualTo(userName);
        AccountTbl accountTbl = accountTblMapper.selectByExample(tblExample).get(0);
        //2.判空
        if (ObjectUtils.isEmpty(accountTbl)){
            throw  new IllegalArgumentException("账户不存在");
        }
        //3.改变金额并插入到数据库表中
        int idelMoney = accountTbl.getMoney() - money;
        if (idelMoney<0){
            throw new RuntimeException("余额不足");
        }
        accountTbl.setMoney(idelMoney);
        accountTblMapper.updateByPrimaryKeySelective(accountTbl);
        log.info("扣减账户{}成功 , 余额为{} ", userName,idelMoney);

        if ("SXT_USER_2".equals(userName)){
            throw new RuntimeException("抛出异常 ,测试分布式事务Seata");
        }
    }
}